/**
 * 纹理调试辅助工具
 * 用于检查场景中所有纹理的过滤设置
 */

import * as THREE from '../../lib/three/build/three.module.js';

export class TextureDebugHelper {
    /**
     * 扫描场景中所有纹理并输出其设置
     * @param {THREE.Scene} scene - 场景对象
     * @param {THREE.WebGLRenderer} renderer - 渲染器对象
     */
    static debugAllTextures(scene, renderer) {
        console.log('🔍 ===== 纹理调试信息 =====');
        
        const maxAnisotropy = renderer ? renderer.capabilities.getMaxAnisotropy() : 'N/A';
        console.log(`📊 GPU 最大各向异性级别: ${maxAnisotropy}`);
        console.log('');
        
        const textures = new Map(); // 用于去重
        let textureCount = 0;
        
        // 遍历场景中的所有物体
        scene.traverse((object) => {
            if (object.isMesh && object.material) {
                const materials = Array.isArray(object.material) ? object.material : [object.material];
                
                materials.forEach((material) => {
                    // 检查所有可能的纹理属性
                    const textureProps = [
                        'map', 'normalMap', 'bumpMap', 'aoMap', 
                        'emissiveMap', 'metalnessMap', 'roughnessMap', 
                        'displacementMap', 'alphaMap', 'envMap'
                    ];
                    
                    textureProps.forEach(prop => {
                        const texture = material[prop];
                        if (texture && texture.isTexture) {
                            // 使用纹理 UUID 去重
                            if (!textures.has(texture.uuid)) {
                                textures.set(texture.uuid, {
                                    texture,
                                    prop,
                                    materialName: material.name || '未命名材质',
                                    objectName: object.name || '未命名物体'
                                });
                            }
                        }
                    });
                });
            }
        });
        
        // 输出每个纹理的详细信息
        console.log(`📷 找到 ${textures.size} 个唯一纹理：\n`);
        
        textures.forEach((info, uuid) => {
            const { texture, prop, materialName, objectName } = info;
            textureCount++;
            
            console.log(`--- 纹理 #${textureCount} ---`);
            console.log(`  物体: ${objectName}`);
            console.log(`  材质: ${materialName}`);
            console.log(`  类型: ${prop}`);
            console.log(`  UUID: ${uuid}`);
            
            if (texture.image) {
                console.log(`  尺寸: ${texture.image.width} x ${texture.image.height}`);
                
                // 检查是否是2的幂次方
                const isPowerOfTwo = this.isPowerOfTwo(texture.image.width) && 
                                    this.isPowerOfTwo(texture.image.height);
                console.log(`  2的幂次方: ${isPowerOfTwo ? '✅' : '⚠️ 否（可能影响 Mipmap）'}`);
            }
            
            // 过滤器设置
            console.log(`  过滤器设置:`);
            console.log(`    - minFilter: ${this.getFilterName(texture.minFilter)} ${this.validateMinFilter(texture.minFilter)}`);
            console.log(`    - magFilter: ${this.getFilterName(texture.magFilter)} ${this.validateMagFilter(texture.magFilter)}`);
            console.log(`    - anisotropy: ${texture.anisotropy} ${this.validateAnisotropy(texture.anisotropy, maxAnisotropy)}`);
            
            // Mipmap 设置
            console.log(`  Mipmap:`);
            console.log(`    - generateMipmaps: ${texture.generateMipmaps ? '✅' : '❌'}`);
            console.log(`    - mipmaps 数量: ${texture.mipmaps ? texture.mipmaps.length : 0}`);
            
            // 其他重要属性
            console.log(`  其他:`);
            console.log(`    - wrapS: ${this.getWrapName(texture.wrapS)}`);
            console.log(`    - wrapT: ${this.getWrapName(texture.wrapT)}`);
            console.log(`    - colorSpace: ${this.getColorSpaceName(texture.colorSpace)}`);
            console.log('');
        });
        
        // 提供优化建议
        this.provideSuggestions(textures, maxAnisotropy);
        
        console.log('🔍 ===== 调试信息结束 =====');
    }
    
    /**
     * 检查数字是否是2的幂次方
     */
    static isPowerOfTwo(value) {
        return (value & (value - 1)) === 0 && value !== 0;
    }
    
    /**
     * 获取过滤器名称
     */
    static getFilterName(filter) {
        const filters = {
            [THREE.NearestFilter]: 'NearestFilter',
            [THREE.NearestMipmapNearestFilter]: 'NearestMipmapNearestFilter',
            [THREE.NearestMipmapLinearFilter]: 'NearestMipmapLinearFilter',
            [THREE.LinearFilter]: 'LinearFilter',
            [THREE.LinearMipmapNearestFilter]: 'LinearMipmapNearestFilter',
            [THREE.LinearMipmapLinearFilter]: 'LinearMipmapLinearFilter'
        };
        return filters[filter] || `Unknown (${filter})`;
    }
    
    /**
     * 获取包裹模式名称
     */
    static getWrapName(wrap) {
        const wraps = {
            [THREE.RepeatWrapping]: 'RepeatWrapping',
            [THREE.ClampToEdgeWrapping]: 'ClampToEdgeWrapping',
            [THREE.MirroredRepeatWrapping]: 'MirroredRepeatWrapping'
        };
        return wraps[wrap] || `Unknown (${wrap})`;
    }
    
    /**
     * 获取色彩空间名称
     */
    static getColorSpaceName(colorSpace) {
        const spaces = {
            [THREE.NoColorSpace]: 'NoColorSpace',
            [THREE.SRGBColorSpace]: 'SRGBColorSpace',
            [THREE.LinearSRGBColorSpace]: 'LinearSRGBColorSpace'
        };
        return spaces[colorSpace] || `Unknown (${colorSpace})`;
    }
    
    /**
     * 验证 minFilter 设置
     */
    static validateMinFilter(filter) {
        if (filter === THREE.LinearMipmapLinearFilter) {
            return '✅ (推荐)';
        } else if (filter === THREE.LinearFilter || filter === THREE.NearestFilter) {
            return '⚠️ (未使用 Mipmap)';
        }
        return '⚠️';
    }
    
    /**
     * 验证 magFilter 设置
     */
    static validateMagFilter(filter) {
        if (filter === THREE.LinearFilter) {
            return '✅ (推荐)';
        } else if (filter === THREE.NearestFilter) {
            return '⚠️ (会产生像素化)';
        }
        return '⚠️';
    }
    
    /**
     * 验证 anisotropy 设置
     */
    static validateAnisotropy(value, maxValue) {
        if (value >= maxValue) {
            return '✅ (最大值)';
        } else if (value >= 4) {
            return '✔️ (较高)';
        } else if (value > 1) {
            return '⚠️ (较低)';
        } else {
            return '❌ (未启用)';
        }
    }
    
    /**
     * 提供优化建议
     */
    static provideSuggestions(textures, maxAnisotropy) {
        console.log('💡 ===== 优化建议 =====');
        
        let hasIssues = false;
        const issues = {
            lowAnisotropy: [],
            noMipmaps: [],
            wrongFilter: [],
            nonPowerOfTwo: []
        };
        
        textures.forEach((info, uuid) => {
            const { texture, materialName, objectName } = info;
            const label = `${objectName} / ${materialName}`;
            
            // 检查各向异性
            if (texture.anisotropy < maxAnisotropy) {
                issues.lowAnisotropy.push(label);
            }
            
            // 检查 Mipmap
            if (!texture.generateMipmaps) {
                issues.noMipmaps.push(label);
            }
            
            // 检查过滤器
            if (texture.minFilter !== THREE.LinearMipmapLinearFilter || 
                texture.magFilter !== THREE.LinearFilter) {
                issues.wrongFilter.push(label);
            }
            
            // 检查纹理尺寸
            if (texture.image) {
                const isPOT = this.isPowerOfTwo(texture.image.width) && 
                             this.isPowerOfTwo(texture.image.height);
                if (!isPOT) {
                    issues.nonPowerOfTwo.push(label);
                }
            }
        });
        
        // 输出建议
        if (issues.lowAnisotropy.length > 0) {
            hasIssues = true;
            console.log(`\n⚠️ 以下纹理的各向异性过滤级别较低（当前最大值: ${maxAnisotropy}）：`);
            issues.lowAnisotropy.forEach(label => console.log(`   - ${label}`));
            console.log('   建议: texture.anisotropy = maxAnisotropy');
        }
        
        if (issues.noMipmaps.length > 0) {
            hasIssues = true;
            console.log(`\n⚠️ 以下纹理未启用 Mipmap 生成：`);
            issues.noMipmaps.forEach(label => console.log(`   - ${label}`));
            console.log('   建议: texture.generateMipmaps = true');
        }
        
        if (issues.wrongFilter.length > 0) {
            hasIssues = true;
            console.log(`\n⚠️ 以下纹理未使用推荐的过滤器设置：`);
            issues.wrongFilter.forEach(label => console.log(`   - ${label}`));
            console.log('   建议: minFilter = LinearMipmapLinearFilter, magFilter = LinearFilter');
        }
        
        if (issues.nonPowerOfTwo.length > 0) {
            hasIssues = true;
            console.log(`\n⚠️ 以下纹理的尺寸不是2的幂次方（可能影响 Mipmap 性能）：`);
            issues.nonPowerOfTwo.forEach(label => console.log(`   - ${label}`));
            console.log('   建议: 使用 2的幂次方 尺寸（256, 512, 1024, 2048, 4096 等）');
        }
        
        if (!hasIssues) {
            console.log('\n✅ 所有纹理设置都是最优的！');
        }
        
        console.log('💡 ===== 建议结束 =====\n');
    }
}

// 暴露到全局，方便在控制台调用
if (typeof window !== 'undefined') {
    window.TextureDebugHelper = TextureDebugHelper;
    
    // 提供快捷方法
    window.debugTextures = function() {
        if (window.manager) {
            TextureDebugHelper.debugAllTextures(window.manager.scene, window.manager.renderer);
        } else {
            console.error('❌ window.manager 未找到');
        }
    };
    
    console.log('💡 纹理调试工具已加载！在控制台输入 debugTextures() 查看纹理设置');
}

export default TextureDebugHelper;

